package thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ComDemo {


	public static void main(String[] args) throws ExecutionException, InterruptedException {
//		CompletableFuture.supplyAsync(()->1)
//				.thenApply(i -> i+3)
//				.thenApply(i -> i+i)
//				.whenComplete((r,e) -> System.out.println(r+","+e))
//				.thenRun(()-> System.out.println("heiheihei "));
//		thenApply();

//		thenCompose();
//		thenCombine();
//		demo();
		composeDemo();
	}

	public static void composeDemo() throws ExecutionException, InterruptedException {
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
			return 100;
		});
		CompletableFuture<String> f = future.thenCompose( i -> {
			return CompletableFuture.supplyAsync(() -> {
				return (i * 10) + "";
			});
		});
		System.out.println(f.get()); //1000
	}
	public static void demo() {
		CompletableFuture future = CompletableFuture.supplyAsync(()-> 1+1)
					.thenApply(a-> a+1);

		try {
			Integer result = (Integer) future.get();
			System.out.println(result);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	public static void thenApply() throws ExecutionException, InterruptedException {
		CompletableFuture<String> future = CompletableFuture.supplyAsync(()->1)
				.thenApply(i -> String.valueOf(i+1));
		String s = future.get();
		System.out.println(s);
	}
	public static void thenCombine() {
		CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello ")   //第一个CompletableFuture返回结果
				.thenCombine(CompletableFuture.supplyAsync(() -> 1),          //第二个CompletableFuture返回结果
						(future1, future2) -> future1 + future2);      //处理两个结果的逻辑
		String join = future.join();
		System.out.println(join); //Hello World
	}

	public static void thenCompose() {
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 1) //提供第一个CompletableFuture结果值
				.thenCompose((i) ->    //将上一个结果值传入下一个CompletableFuture
						CompletableFuture.supplyAsync(() -> i + 2));  //对传入的结果值进行处理
		Integer join = future.join();
		System.out.println(join);
	}

	public static String func(Integer i){
		System.out.println("future"+i);
		return "str "+ i;
	}
}
